package v1

import (
	"gin-example/models"
	"gin-example/pkg/e"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/thedevsaddam/gojsonq/v2"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
)

func AddBCUCollect(c *gin.Context) {
	body, _ := ioutil.ReadAll(c.Request.Body)
	bcuId := gojsonq.New().FromString(string(body)).Find("bcuId")
	voltages := gojsonq.New().FromString(string(body)).Find("volt")
	soc := gojsonq.New().FromString(string(body)).Find("soc")
	insulation := gojsonq.New().FromString(string(body)).Find("insu")
	valid := validation.Validation{}
	valid.Required(bcuId, "bcuId").Message("bcuId不能为空")
	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.ERROR_NOT_EXIST
		tmpBCUId, _ := strconv.Atoi(bcuId.(string))
		if models.ExistBCUById(tmpBCUId) {
			code = e.SUCCESS
			if voltages != nil {
				for _, voltage := range voltages.([]interface{}) {
					tmpPointId, _ := strconv.Atoi(voltage.(map[string]interface{})["id"].(string))
					tmpVoltage := voltage.(map[string]interface{})["val"].(float64)
					models.AddBCUVoltage(tmpPointId, tmpBCUId, tmpVoltage)
				}
			}

			if soc != nil {
				models.AddBCUSoc(tmpBCUId, soc.(float64))
			}

			if insulation != nil {
				models.AddBCUInsulation(tmpBCUId, insulation.(float64))
			}
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func GetBCUOutline(c *gin.Context) {
	data := make(map[string]interface{})
	bcuId := c.Query("bcuId")
	valid1 := validation.Validation{}
	valid1.Required(bcuId, "bcuId").Message("bcuId不能为空")
	code := e.INVALID_PARAMS
	if !valid1.HasErrors() {
		code = e.ERROR_NOT_EXIST
		tmpBCUId, _ := strconv.Atoi(bcuId)
		if models.ExistBCUById(tmpBCUId) {
			code = e.SUCCESS
			data = models.GetBCUOutline(tmpBCUId)
		}
	} else {
		for _, err := range valid1.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}

func GetBCUCollects(c *gin.Context) {
	var data []models.BCUCollect
	bcuId := c.Query("bcuId")
	duration := c.Query("duration")
	valid1 := validation.Validation{}
	valid1.Required(bcuId, "bcuId").Message("bcuId不能为空")
	valid1.Required(duration, "duration").Message("duration不能为空")
	code := e.INVALID_PARAMS
	if !valid1.HasErrors() {
		code = e.ERROR_NOT_EXIST
		tmpBCUId, _ := strconv.Atoi(bcuId)
		tmpDuration, _ := strconv.Atoi(duration)
		if models.ExistBCUById(tmpBCUId) {
			code = e.SUCCESS
			data = models.GetBCUCollects(tmpBCUId, tmpDuration)
		}
	} else {
		for _, err := range valid1.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}